import pygame
import sys
import random
from PIL import Image
import socket
import time
import threading
from pygame.locals import *
hit_sound = None
eat_sound = None

class net_work:
    def __init__(self):
        self.connected=False
        self.server_socket=None
        self.client_socket=None
        self.thread=None
        self.lock=threading.Lock()
    def start_server(self):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind((server_client.IP, server_client.PORT))
        self.server_socket.listen(2)
        self.server_socket.settimeout(30)

        if self.connected:
            try:
                with self.lock:
                    self.client_socket, addr = self.server_socket.accept()
                    self.connected = True
                    print(f"成功链接对方{addr}")
                self.client_socket.send("hello".encode())
                with self.lock:

                    self.data = self.client_socket.recv(1024).decode()
                    print(f"新的消息{self.data}")
            except socket.timeout:
                self.server_socket.close()
            finally:
                self.server_socket.close()
    def accept_client(self):
        if not self.thread:
            self.thread = threading.Thread(target=self.start_server)
            self.thread.daemon=True
            self.thread.start()
    def close_socket(self):
        if  self.client_socket:
            self.client_socket.close()
        if self.server_socket:
            self.server_socket.close()
        self.thread=None

class server_client:
    IP = '127.0.0.1'
    PORT=8080

# 游戏配置常量
class Config:
    DEBUG_MODE = False
    SCREEN_WIDTH = 900  # 初始窗口大小
    SCREEN_HEIGHT = 600
    FPS = 60
    # 网格设置
    GRID_START_X = 253  # 网格起始X坐标保持不变
    GRID_START_Y = 80  # 网格起始Y坐标保持不变
    GRID_END_X = 894  # 初始网格结束X坐标
    GRID_END_Y = 580  # 初始网格结束Y坐标
    GRID_COLS = 9  # 8列
    GRID_ROWS = 5  # 5行
    # 计算每个格子的大小
    GRID_WIDTH = (GRID_END_X - GRID_START_X) // GRID_COLS
    GRID_HEIGHT = (GRID_END_Y - GRID_START_Y) // GRID_ROWS
    # 僵尸攻击设置
    ZOMBIE_ATTACK_DAMAGE = 10  # 每次攻击伤害
    ZOMBIE_ATTACK_COOLDOWN = 1000  # 攻击冷却时间(毫秒)

    CAR_START_X=173  #小推车网格起始x坐标
    CAR_END_X=253     #小推车终点x坐标
    CAR_START_Y=80     #小推车起始y坐标
    CAR_END_Y=573       #小推车终点y坐标
    CAR_COLS = 1
    CAR_ROWS = 5
    CAR_TRIGGER_LINE = 173
    CAR_SPEED = 10


    # 计算宽高
    CAR_WIDTH = (CAR_END_X - CAR_START_X) // CAR_COLS
    CAR_HEIGHT = (CAR_END_Y - CAR_START_Y) // CAR_ROWS
    #小车碰撞框
    CAR_HITBOX_OFFSET_X = 10  # 碰撞框左侧偏移
    CAR_HITBOX_OFFSET_Y = 10  # 碰撞框顶部偏移
    CAR_HITBOX_WIDTH_OFFSET = -20  # 碰撞框宽度调整(图片宽度减去这个值)
    CAR_HITBOX_HEIGHT_OFFSET = -20  # 碰撞框高度调整(图片高度减去这个值)




def extracting_gif(gif_path):
    frames = []
    try:
        img = Image.open(gif_path)
        for i in range(img.n_frames):
            img.seek(i)
            frame = img.copy()
            if frame.mode != 'RGBA':
                frame = frame.convert('RGBA')
            frames.append(frame)
    except Exception as e:
        print(f"Error loading GIF {gif_path}: {e}")
    return frames


def load_gif(frames):
    pygame_frames = []
    for frame in frames:
        try:
            mode = frame.mode
            size = frame.size
            data = frame.tobytes()
            pygame_frame = pygame.image.fromstring(data, size, mode)
            pygame_frames.append(pygame_frame)
        except Exception as e:
            print(f"Error converting frame: {e}")
    return pygame_frames


class Zombie:
    def __init__(self, x, y, life, speed, move_frames, attack_frames):
        self.x = x
        self.y = y
        self.life = 40
        self.speed = speed
        self.move_frames = move_frames
        self.attack_frames = attack_frames
        self.current_frames = move_frames
        self.current_frame = 0
        self.last_update = pygame.time.get_ticks()
        self.last_attack_time = 0
        self.is_attacking = False
        self.attack_target = None

        # 计算僵尸图片面积大小
        if move_frames:
            frame_width = move_frames[0].get_width()
            frame_height = move_frames[0].get_height()
        else:
            frame_width = 80
            frame_height = 100

        # 绿色受击框 - 取图片下半部分
        left_offset = 30  # 左侧向右偏移30像素
        top_offset = frame_height // 2  # 关键修改：从图片垂直中点开始
        right_offset = 2  # 右偏移2像素
        bottom_offset = 0  # 下偏移0像素

        # 计算受击框高度（取下半部分高度）
        hitbox_height = frame_height // 2  # 直接使用半高

        self.hitbox = (
            left_offset,  # 左侧向右偏移
            top_offset,  # 从图片中点开始（取下半部分）
            frame_width - left_offset - right_offset,  # 宽度不变
            hitbox_height  # 高度为原图一半
        )

        # 红色攻击框 - 同步调整到下半部分
        attackbox_width = 15  # 攻击框宽度
        self.attack_range = (
            15,  # 紧贴绿色框左侧
            self.hitbox[1],  # 上边界与受击框一致（图片中点）
            attackbox_width,  # 宽度不变
            self.hitbox[3]  # 高度同步为下半部分
        )

        # 初始化碰撞框（下半部分）
        self.rect = pygame.Rect(
            x + self.hitbox[0],
            y + self.hitbox[1],  # y起始位置为图片中点
            self.hitbox[2],
            self.hitbox[3]
        )

        # 初始化攻击范围框（下半部分）
        self.attack_rect = pygame.Rect(
            x + self.attack_range[0],
            y + self.attack_range[1],  # 同步图片中点
            self.attack_range[2],
            self.attack_range[3]
        )

    def update(self, plants, bullets):
        now = pygame.time.get_ticks()
        hit_sound = pygame.mixer.Sound('hit.wav')
        hit_sound.set_volume(0.5)
        # 更新碰撞框位置
        self.rect.x = self.x + self.hitbox[0]
        self.rect.y = self.y + self.hitbox[1]
        self.attack_rect.x = self.x + self.attack_range[0]
        self.attack_rect.y = self.y + self.attack_range[1]

        # 检查子弹是否击中僵尸的绿色碰撞框
        for bullet in bullets[:]:
            if bullet.rect.colliderect(self.rect):
                self.life -= bullet.damage
                bullets.remove(bullet)
                if hit_sound:
                    hit_sound.play()
                if self.life <= 0:
                    return  # 僵尸死亡，不再执行后续逻辑

        # 检查是否在攻击范围内（红色攻击框与植物的碰撞框相交）
        self.is_attacking = False
        self.attack_target = None

        for plant in plants:
            if plant.life > 0 and self.attack_rect.colliderect(plant.rect):
                self.is_attacking = True
                self.attack_target = plant
                break

        # 切换动画帧
        if self.is_attacking:
            self.current_frames = self.attack_frames
            # 执行攻击
            if now - self.last_attack_time > Config.ZOMBIE_ATTACK_COOLDOWN:
                if self.attack_target:
                    self.attack_target.life -= Config.ZOMBIE_ATTACK_DAMAGE
                    if eat_sound:
                        eat_sound.play()
                self.last_attack_time = now
        else:
            self.current_frames = self.move_frames
            # 移动
            self.x -= self.speed
            # 更新碰撞框位置（因为x坐标改变了）
            self.rect.x = self.x + self.hitbox[0]
            self.attack_rect.x = self.x + self.attack_range[0]

        # 更新动画帧
        if now - self.last_update > 150:
            self.current_frame = (self.current_frame + 1) % len(self.current_frames)
            self.last_update = now

    def draw(self, screen):
        if 0 <= self.current_frame < len(self.current_frames):
            screen.blit(self.current_frames[self.current_frame], (self.x, self.y))
            if Config.DEBUG_MODE:
                # 绘制绿色受击框
                pygame.draw.rect(screen, (0, 255, 0), self.rect, 1)
                # 绘制红色攻击范围框
                pygame.draw.rect(screen, (255, 0, 0), self.attack_rect, 1)


class Bullet:
    def __init__(self, x, y, speed, damage,bullet_type="bullet"):
        self.x = x
        self.y = y
        self.speed = speed
        self.damage = damage
        self.collision_box = (10, 5, 15, 10)
        self.bullet_type=bullet_type
        self.rect = pygame.Rect(
            x + self.collision_box[0],
            y + self.collision_box[1],
            self.collision_box[2],
            self.collision_box[3]
        )

    def update(self):
        self.x += self.speed
        self.rect.x = self.x + self.collision_box[0]

    def draw(self, screen, image):
        screen.blit(image, (self.x, self.y))
        if Config.DEBUG_MODE:
            pygame.draw.rect(screen, (0, 255, 255), self.rect, 1)

class car:
    def __init__(self, x, y, speed, damage,image):
        self.x = x
        self.y = y
        self.speed = speed
        self.damage = damage
        self.cars=[]
        self.row=0
        self.is_move=False
        self.collision_box = (0, 5, 70, 55)
        self.image = image
        self.rect = pygame.Rect(
            x + self.collision_box[0],
            y + self.collision_box[1],
            self.collision_box[2],
            self.collision_box[3]
        )

    def update(self):
        if self.is_move:
            if self.x<Config.GRID_END_X:
                self.x += self.speed
                self.rect.x = self.x + self.collision_box[0]
    def draw(self, screen, image):
        screen.blit(self.image, (self.x, self.y))
        if Config.DEBUG_MODE:
            pygame.draw.rect(screen, (0, 255, 255), self.rect, 1)




class Sun:
    def __init__(self, x, y, frames):
        self.x = x
        self.y = y
        self.frames = frames
        self.current_frame = 0
        self.last_update = pygame.time.get_ticks()
        self.collected = False
        self.rect = pygame.Rect(x, y, frames[0].get_width(), frames[0].get_height())
        self.spawn_time = pygame.time.get_ticks()
        self.lifetime = 10000  # 阳光存在时间(毫秒)

    def update(self):
        now = pygame.time.get_ticks()

        # 更新动画帧
        if now - self.last_update > 100:
            self.current_frame = (self.current_frame + 1) % len(self.frames)
            self.last_update = now

        # 更新碰撞框位置
        self.rect.x = self.x
        self.rect.y = self.y

        # 检查是否超时消失
        if now - self.spawn_time > self.lifetime:
            self.collected = True

    def draw(self, screen):
        if 0 <= self.current_frame < len(self.frames) and not self.collected:
            screen.blit(self.frames[self.current_frame], (self.x, self.y))
            if Config.DEBUG_MODE:
                pygame.draw.rect(screen, (255, 255, 0), self.rect, 1)



class Plant:
    def __init__(self, x, y, frames, plant_type="pea"):
        self.x = x
        self.y = y
        self.frames = frames
        self.current_frame = 0
        self.last_update = pygame.time.get_ticks()
        self.last_shoot_time = 0
        self.last_sun_time = 0
        self.shoot_cooldown = 1000
        self.sun_cooldown = 10000  # 10秒产生一个阳光
        self.shoot_frame = 2
        self.plant_type = plant_type  # "pea" 或 "kui"
        if plant_type == "pea":
            self.life=80
        elif plant_type == "double_pea":
            self.life=1000
        elif plant_type == "kui":
            self.life=50
        elif plant_type == "ice_pea":
            self.life=100
        # 植物碰撞框
        self.collision_box = (10, 10, 50, 70)
        self.rect = pygame.Rect(
            x + self.collision_box[0],
            y + self.collision_box[1],
            self.collision_box[2],
            self.collision_box[3]
        )

    def update(self, current_time, bullets, bullet_image, suns, sun_frames):
        # 更新碰撞框位置
        self.rect.x = self.x + self.collision_box[0]
        self.rect.y = self.y + self.collision_box[1]

        if current_time - self.last_update > 100:
            self.current_frame = (self.current_frame + 1) % len(self.frames)
            self.last_update = current_time

        # 豌豆射手发射子弹
        if (self.plant_type in ("pea", "double_pea","ice_pea") and  # 同时适用于普通豌豆和双重射手
                current_time - self.last_shoot_time > self.shoot_cooldown and
                self.current_frame == self.shoot_frame and
                self.life > 0):

            mouth_x = self.x + self.frames[self.current_frame].get_width() * 0.8
            mouth_y = self.y + self.frames[self.current_frame].get_height() * 0.15

            if self.plant_type == "pea":
                # 普通豌豆：发射一颗子弹
                bullets.append(Bullet(mouth_x, mouth_y, 5, 20))  # 速度5，伤害20
            elif self.plant_type == "double_pea":
                # 双重射手：发射两颗子弹（上下错开）
                bullets.append(Bullet(mouth_x-20, mouth_y, 5, 20))  # 第一颗子弹（偏上）

                bullets.append(Bullet(mouth_x, mouth_y, 5, 20))  # 第二颗子弹（偏下）
            elif self.plant_type == "ice_pea":
                # 双重射手：发射两颗子弹（上下错开）
                bullets.append(Bullet(mouth_x-20, mouth_y, 5, 20))  # 第一颗子弹（偏上）

                bullets.append(Bullet(mouth_x, mouth_y, 5, 20))  # 第二颗子弹（偏下）

            self.last_shoot_time = current_time
        # 向日葵产生阳光
        if (self.plant_type == "kui" and
                current_time - self.last_sun_time > self.sun_cooldown and
                self.life > 0):  # 只有活着才能产生阳光
            sun_x = self.x + random.randint(-20, 20)
            sun_y = self.y - 20
            suns.append(Sun(sun_x, sun_y, sun_frames))
            self.last_sun_time = current_time

    def draw(self, screen):
        if 0 <= self.current_frame < len(self.frames):
            if self.life > 0:  # 只有活着才绘制
                screen.blit(self.frames[self.current_frame], (self.x, self.y))
                if Config.DEBUG_MODE:
                    pygame.draw.rect(screen, (0, 0, 255), self.rect, 1)
            else:  # 植物死亡
                dead_surface = self.frames[self.current_frame].copy()
                dead_surface.fill((100, 100, 100, 150), special_flags=pygame.BLEND_MULT)
                screen.blit(dead_surface, (self.x, self.y))


def main():
    pygame.init()
    pygame.mixer.init()
    game_mode="plant"
    try:
        # 初始窗口大小 900x600
        screen = pygame.display.set_mode((Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT), pygame.DOUBLEBUF)
        pygame.display.set_caption("植物大战僵尸 - 贝利亚奶龙版")

        # 加载资源
        def load_image(path, alpha=True):
            try:
                image = pygame.image.load(path)
                return image.convert_alpha() if alpha else image.convert()
            except Exception as e:
                print(f"Error loading image {path}: {e}")
                surf = pygame.Surface((50, 50), pygame.SRCALPHA)
                pygame.draw.rect(surf, (255, 0, 0), (0, 0, 50, 50), 2)
                return surf

        image_new_button=load_image("corpse_game.png")
        image_button = load_image('game_start.png')
        button_rect = image_button.get_rect(topleft=(500, 100))#主按钮
        new_button_rect = image_new_button.get_rect(topleft=(550, 300))#僵尸按钮
        background_image = load_image('menu.png')
        game_background = load_image('background.png')
        bullet_image = load_image('bullet.gif')
        tool_image = load_image('toolbar.png')
        car_image=load_image('car.png')#小推车
        ice_bullet_image=load_image('ice_bullet.gif')#冰冻子弹



        # 加载卡片图片
        card_pea_image = load_image('choose/pea.png')
        card_kui_image = load_image('choose/kui.png')
        card_double_pea_image= load_image('choose/double_pea.png')
        card_ice_pea_image=load_image('choose/ice_pea.png')
        # 计算卡片位置 - 无缝贴图
        pea_card_width = card_pea_image.get_width()
        card_pea_pos = (340, 0)
        card_kui_pos = (card_pea_pos[0] + pea_card_width, card_pea_pos[1])
        card_double_pea_pos = (card_kui_pos[0]+pea_card_width, card_kui_pos[1])
        card_ice_pea_pos=(card_double_pea_pos[0]+pea_card_width, card_double_pea_pos[1])
        # 按钮动画效果
        button_original_size = button_rect.size
        button_shrink_size = (button_original_size[0] * 0.8, button_original_size[1] * 0.8)
        button_shrink_rect = button_rect.copy()
        button_shrink_rect.size = button_shrink_size
        button_shrink_rect.center = button_rect.center
        #僵尸按钮动画效果
        new_button_size = new_button_rect.size
        new_button_shrink_size =(new_button_size[0] * 0.8, new_button_size[1] * 0.8)
        new_button_shrink_rect = button_rect.copy()
        new_button_shrink_rect.size = new_button_shrink_size
        new_button_shrink_rect.center=new_button_rect.center



        # 加载动画
        pea_frames = extracting_gif('wandou.gif')
        pea_pygame_frames = load_gif(pea_frames)
        kui_frames = extracting_gif('kui.gif')
        kui_pygame_frames = load_gif(kui_frames)
        corpse_move_frames = extracting_gif('corpse_move.gif')
        corpse_move_pygame_frames = load_gif(corpse_move_frames)
        corpse_eat_frames = extracting_gif('corpse_eat.gif')
        corpse_eat_pygame_frames = load_gif(corpse_eat_frames)
        sun_image_frames = extracting_gif('sun.gif')
        sun_pygame_frames = load_gif(sun_image_frames)
        double_pea_frames = extracting_gif('double_pea.gif')
        double_pea_pygame_frames = load_gif(double_pea_frames)
        ice_pea_frames= extracting_gif('ice_pea.gif')
        ice_pea_pygame_frames=load_gif(ice_pea_frames)


        # 音效
        def load_sound(path):
            try:
                return pygame.mixer.Sound(path)
            except Exception as e:
                print(f"Error loading sound {path}: {e}")
                return None

        pygame.mixer.music.load('music.ogg')
        pygame.mixer.music.play(-1)
        click_sound = load_sound('corpse_music.wav')
        hit_sound = load_sound('hit.wav')
        place_sound = load_sound('place.wav')
        sun_sound = load_sound('sun.wav')
        eat_sound = load_sound('eat.wav')
        corpse_sound = load_sound('corpse_start.wav')
        # 游戏变量
        zombies = []
        bullets = []
        plants = []
        suns = []
        sun_value = 50
        cars=[]
        # 游戏状态
        network1 = True
        running = True
        button_pressed = False
        new_button_pressed = False
        switch_background = False
        music_playing = False
        switch_time = 0
        car_playing=True
        game_started = False
        last_zombie_spawn = 0
        zombie_spawn_cooldown = 5000
        new_music_button=False
        corpse_game=False#僵尸游戏状态
        car_x=173
        car_y=83+0.5*Config.CAR_HEIGHT
        car_temp=car_y
        # 拖动相关变量
        dragging = False
        drag_card_pos = (0, 0)
        drag_offset = (0, 0)
        dragging_card_type = None
        valid_placement = False

        # 字体
        font = pygame.font.SysFont('Arial', 18)

        clock = pygame.time.Clock()

        def get_grid_position(pos):
            """将屏幕坐标转换为网格坐标"""
            x, y = pos
            if not (Config.GRID_START_X <= x <= Config.GRID_END_X and
                    Config.GRID_START_Y <= y <= Config.GRID_END_Y):
                return None

            grid_x = (x - Config.GRID_START_X) // Config.GRID_WIDTH
            grid_y = (y - Config.GRID_START_Y) // Config.GRID_HEIGHT

            if 0 <= grid_x < Config.GRID_COLS and 0 <= grid_y < Config.GRID_ROWS:
                return (
                    Config.GRID_START_X + grid_x * Config.GRID_WIDTH,
                    Config.GRID_START_Y + grid_y * Config.GRID_HEIGHT
                )
            return None


        def is_position_valid(pos):
            """检查位置是否在网格内且未被占用"""
            grid_pos = get_grid_position(pos)
            if grid_pos is None:
                return False

            for plant in plants:
                plant_grid_pos = get_grid_position((plant.x, plant.y))
                if plant_grid_pos == grid_pos and plant.life > 0:
                    return False

            return True

        while running:
            current_time = pygame.time.get_ticks()
            clock.tick(Config.FPS)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if not music_playing and button_rect.collidepoint(event.pos):
                        button_pressed = True

                        if click_sound:
                            click_sound.play()
                        switch_time = current_time + 3000
                        music_playing = True
                    elif not new_music_button and new_button_rect.collidepoint(event.pos):
                        new_button_pressed = True
                        if corpse_sound:
                            corpse_sound.play()
                        switch_time = current_time + 3000
                        game_mode="corpse"
                        music_playing = True

                    elif game_started:
                        card_pea_rect = pygame.Rect(card_pea_pos, card_pea_image.get_size())
                        card_kui_rect = pygame.Rect(card_kui_pos, card_kui_image.get_size())
                        card_double_rect=pygame.Rect(card_double_pea_pos,card_double_pea_image.get_size())
                        card_ice_rect=pygame.Rect(card_ice_pea_pos,card_ice_pea_image.get_size())


                        if card_double_rect.collidepoint(event.pos):#双重豌豆射手拖动逻辑
                            dragging=True
                            dragging_card_type="double_pea"
                            drag_offset = (event.pos[0] - card_double_pea_pos[0],
                                           event.pos[1] - card_double_pea_pos[1])
                            drag_card_pos=card_double_pea_pos

                        elif card_ice_rect.collidepoint(event.pos):
                            dragging=True
                            dragging_card_type="ice_pea"
                            drag_offset = (event.pos[0] - card_ice_pea_pos[0],
                                           event.pos[1] - card_ice_pea_pos[1])
                            drag_card_pos=card_ice_pea_pos

                        elif card_pea_rect.collidepoint(event.pos):#普通豌豆射手拖动逻辑
                            dragging = True
                            dragging_card_type = "pea"
                            drag_offset = (event.pos[0] - card_pea_pos[0],
                                           event.pos[1] - card_pea_pos[1])
                            drag_card_pos = card_pea_pos


                        elif card_kui_rect.collidepoint(event.pos):#向日葵拖动逻辑
                            dragging = True
                            dragging_card_type = "kui"
                            drag_offset = (event.pos[0] - card_kui_pos[0],
                                           event.pos[1] - card_kui_pos[1])
                            drag_card_pos = card_kui_pos

                        else:
                            for sun in suns[:]:
                                if sun.rect.collidepoint(event.pos) and not sun.collected:
                                    sun.collected = True
                                    sun_value += 200
                                    if sun_sound:
                                        sun_sound.play()
                                    suns.remove(sun)
                elif event.type == pygame.MOUSEBUTTONUP:
                    button_pressed = False
                    new_button_pressed = False
                    if dragging:
                        dragging = False
                        if valid_placement:
                            grid_pos = get_grid_position(event.pos)
                            if grid_pos and game_mode=="plant":
                                if dragging_card_type == "pea" and sun_value>=100:
                                    plants.append(Plant(grid_pos[0], grid_pos[1], pea_pygame_frames, "pea"))
                                    sun_value-=100
                                elif dragging_card_type == "kui" and sun_value>=50:
                                    plants.append(Plant(grid_pos[0], grid_pos[1], kui_pygame_frames, "kui"))
                                    sun_value-=50
                                elif dragging_card_type=="double_pea" and sun_value>=200 :
                                    plants.append(Plant(grid_pos[0],grid_pos[1],double_pea_pygame_frames,"double_pea"))
                                    sun_value-=200
                                elif dragging_card_type=="ice_pea" and sun_value>=175:
                                    plants.append(Plant(grid_pos[0],grid_pos[1],ice_pea_pygame_frames,"ice_pea"))
                                    sun_value-=175
                                if place_sound:
                                    place_sound.play()
                        dragging_card_type = None
                        valid_placement = False
                elif event.type == pygame.MOUSEMOTION:
                    if dragging:
                        drag_card_pos = (event.pos[0] - drag_offset[0],
                                         event.pos[1] - drag_offset[1])
                        valid_placement = is_position_valid(event.pos)
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_d:
                        Config.DEBUG_MODE = not Config.DEBUG_MODE

            # 游戏状态更新
            if current_time >= switch_time and switch_time != 0:
                switch_background = True
                switch_time = 0
                game_started = True
                last_zombie_spawn = current_time

                # 切换到1400x600窗口
                Config.SCREEN_WIDTH = 1400
                Config.GRID_END_X = 988  # 更新网格结束坐标
                Config.GRID_END_Y = 570

                # 重新计算网格大小
                Config.GRID_WIDTH = (Config.GRID_END_X - Config.GRID_START_X) // Config.GRID_COLS
                Config.GRID_HEIGHT = (Config.GRID_END_Y - Config.GRID_START_Y) // Config.GRID_ROWS

                # 重新设置窗口大小
                screen = pygame.display.set_mode((Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT), pygame.DOUBLEBUF)


            screen.blit(game_background if switch_background else background_image, (0, 0))

            if switch_background:

                if car_playing:
                    for i in range(1, 6):
                        # screen.blit(car_image,(car_x,car_y-10))

                        new_car = car(car_x, car_y - 15, 100, 1000, car_image)
                        car_y += Config.CAR_HEIGHT
                        cars.append(new_car)
                        if i == 5:
                            car_y = car_temp

                    car_playing = False
                for car1 in cars:
                    car1.update()
                    car1.draw(screen, car_image)


                def check_car_hitbox_collisions():
                    for car in cars:
                        # 更新碰撞框位置（确保 rect 是最新的）
                        car.rect.x = car.x + car.collision_box[0]
                        car.rect.y = car.y + car.collision_box[1]

                        # 检测与僵尸的碰撞
                        for zombie in zombies[:]:
                            if car.rect.colliderect(zombie.rect):
                                car.is_move = True

                                zombies.remove(zombie)
                                if hit_sound:
                                    hit_sound.play()

                                print(f"僵尸在坐标({zombie.rect.x},{zombie.rect.y})被小推车消灭")


                        # 调试绘制
                        if Config.DEBUG_MODE:
                            pygame.draw.rect(screen, (255, 0, 0), car.rect, 1)


                if game_mode=="plant":

                    if network1:
                        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        host = server_client.IP
                        port = server_client.PORT
                        server_socket.bind((host, port))
                        server_socket.listen(2)
                        server_socket.settimeout(3)

                        try:
                            client_socket, addr = server_socket.accept()
                            print(f"连接方{addr}")
                            message = "hello"
                            client_socket.send(message.encode())
                            while 1:
                                data = client_socket.recv(1024).decode()
                                print(f"新的消息{data}")
                        except socket.timeout:
                            print("链接超时")
                            server_socket.close()
                            network1 = False
                        finally:
                            server_socket.close()
                            network1 = False
                            print("已经退出")



                    check_car_hitbox_collisions()
                    pygame.draw.line(
                        screen, (255, 255, 255, 100), (Config.CAR_START_X, Config.CAR_START_Y),
                        (Config.CAR_START_X, Config.CAR_END_Y), 0
                    )
                    pygame.draw.line(
                        screen, "red", (Config.CAR_END_X, Config.CAR_START_Y), (Config.CAR_END_X, Config.CAR_END_Y), 0
                    )
                    for y in range(Config.CAR_START_Y, Config.CAR_END_Y + Config.CAR_HEIGHT, Config.CAR_HEIGHT):
                        pygame.draw.line(
                            screen, (255, 255, 255, 100), (Config.CAR_START_X, y), (Config.CAR_END_X, y), 0
                        )

                    # 绘制垂直网格线
                    for x in range(Config.GRID_START_X, Config.GRID_END_X, Config.GRID_WIDTH):
                        pygame.draw.line(screen, (255, 255, 255, 100), (x, Config.GRID_START_Y),
                                         (x, Config.GRID_END_Y), 0)

                    # 绘制水平网格线
                    for y in range(Config.GRID_START_Y, Config.GRID_END_Y + Config.GRID_HEIGHT, Config.GRID_HEIGHT):
                        pygame.draw.line(screen, (255, 255, 255, 100), (Config.GRID_START_X, y),
                                         (Config.GRID_END_X, y), 0)

                    screen.blit(tool_image, (300, 0))
                    sun_text = font.render(f"{sun_value}", True, (0, 0, 0))  # 黄色文本 可以改成unicode
                    text_rect = sun_text.get_rect(topleft=(300, 35))  # 文本位置（左上角）
                    screen.blit(sun_text, (310, 30))

                    if not dragging or dragging_card_type != "pea":  # 豌豆射手卡牌绘制
                        screen.blit(card_pea_image, card_pea_pos)

                    if not dragging or dragging_card_type != "pea":  # 豌豆射手卡牌绘制
                        screen.blit(card_pea_image, card_pea_pos)

                    if not dragging or dragging_card_type != "kui":  # 向日葵卡牌绘制
                        screen.blit(card_kui_image, card_kui_pos)

                    if not dragging or dragging_card_type != "double_pea":  # 双重射手绘制
                        screen.blit(card_double_pea_image, card_double_pea_pos)

                    if not dragging or dragging_card_type != "ice_pea":  # 双重射手绘制
                        screen.blit(card_ice_pea_image, card_ice_pea_pos)

                    if dragging:
                        if dragging_card_type == "pea":
                            temp_card = card_pea_image.copy()
                        elif dragging_card_type == "kui":
                            temp_card = card_kui_image.copy()
                        elif dragging_card_type == "double_pea":
                            temp_card = card_double_pea_image.copy()
                        elif dragging_card_type == "ice_pea":
                            temp_card = card_ice_pea_image.copy()

                        temp_card.set_alpha(180)
                        screen.blit(temp_card, drag_card_pos)

                        if valid_placement:
                            grid_pos = get_grid_position(pygame.mouse.get_pos())
                            if grid_pos:
                                if dragging_card_type == "pea":
                                    preview = pea_pygame_frames[0].copy() if pea_pygame_frames else None
                                elif dragging_card_type == "kui":
                                    preview = kui_pygame_frames[0].copy() if kui_pygame_frames else None
                                elif dragging_card_type == "double_pea":
                                    preview = double_pea_pygame_frames[0].copy() if double_pea_pygame_frames else None
                                elif dragging_card_type == "ice_pea":
                                    preview = ice_pea_pygame_frames[0].copy() if ice_pea_pygame_frames else None
                                if preview:
                                    preview.set_alpha(150)
                                    screen.blit(preview, grid_pos)

                    sun_text = font.render(f"{sun_value}", True, (0, 0, 0))
                    screen.blit(sun_text, (50, 30))
                elif game_mode=="corpse":
                    #print("这里开始添加僵尸网格以及僵尸卡牌逻辑")
                    check_car_hitbox_collisions()

            if not switch_background:
                screen.blit(
                    pygame.transform.scale(image_button, button_shrink_size) if button_pressed else image_button,
                    button_shrink_rect.topleft if button_pressed else button_rect.topleft
                )
                screen.blit(
                    pygame.transform.scale(image_new_button,new_button_shrink_size) if new_button_pressed else image_new_button,
                    new_button_shrink_rect.topleft if new_button_pressed else new_button_rect.topleft
                )
            if game_started:
                # 修改僵尸生成逻辑
                if game_started:
                    # 修改僵尸生成逻辑
                    if current_time - last_zombie_spawn > zombie_spawn_cooldown:
                        # 跑道总数
                        num_lanes = 5

                        # 跑道区域的顶部和底部边界（整体向上移动一格）
                        lane_top = 80 - (571 - 80) / num_lanes  # 向上移动一格（一个跑道的高度）
                        lane_bottom = 571 - (571 - 80) / num_lanes  # 底部也相应上移

                        # 计算每条跑道的高度（保持不变）
                        lane_height = (lane_bottom - lane_top) / num_lanes

                        # 随机选择一个跑道 (0-4)
                        lane = random.randint(0, num_lanes - 1)

                        # 计算该跑道的Y中心位置
                        y_pos = lane_top + lane * lane_height + lane_height / 2

                        # 确保生成位置在有效范围内（防止最上面的跑道溢出）
                        if y_pos < lane_top:
                            y_pos = lane_top + lane_height / 2  # 如果超出顶部，则放在第一条跑道

                        # 在屏幕右侧外部生成僵尸（X=1200超出可见区域）
                        zombies.append(Zombie(
                            1200,  # 固定X位置（屏幕右侧外部）
                            y_pos,  # 调整后的Y位置
                            50,  # 僵尸宽度
                            1,  # 僵尸速度
                            corpse_move_pygame_frames,
                            corpse_eat_pygame_frames
                        ))
                        last_zombie_spawn = current_time
                plants_to_remove = []
                for plant in plants:
                    plant.update(current_time, bullets, bullet_image, suns, sun_pygame_frames)
                    plant.draw(screen)
                    if plant.life <= 0 and plant not in plants_to_remove:
                        plants_to_remove.append(plant)

                for plant in plants_to_remove:
                    if plant in plants:
                        plants.remove(plant)

                for zombie in zombies[:]:
                    zombie.update(plants, bullets)
                    zombie.draw(screen)
                    if zombie.x < -100 or zombie.life <= 0:
                        zombies.remove(zombie)

                for sun in suns[:]:
                    sun.update()
                    sun.draw(screen)
                    if sun.collected or current_time - sun.spawn_time > sun.lifetime:
                        suns.remove(sun)

                bullets_to_remove = []
                for bullet in bullets[:]:
                    bullet.update()
                    if bullet.x > Config.SCREEN_WIDTH:
                        bullets_to_remove.append(bullet)
                        continue

                for bullet in bullets_to_remove:
                    if bullet in bullets:
                        bullets.remove(bullet)

                for bullet in bullets:
                    bullet.draw(screen, bullet_image)

            pygame.display.flip()

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        pygame.quit()
        sys.exit()


if __name__ == "__main__":
    main()